import axios from 'axios';

// 自定义错误类
export class ApiError extends Error {
    constructor(
        message: string,
        public status?: number,
        public code?: string,
        public data?: any,
        public details?: string,
        public retry?: boolean
    ) {
        super(message);
        this.name = 'ApiError';
        this.retry = retry || false;
        this.details = details || '';
    }
}

// 重试工具函数
export const withRetry = async <T>(
    fn: () => Promise<T>,
    retries: number = 3,
    delay: number = 1000
): Promise<T> => {
    let lastError: Error;
    
    for (let i = 0; i <= retries; i++) {
        try {
            return await fn();
        } catch (error) {
            lastError = error as Error;
            
            if (i === retries) {
                throw lastError;
            }
            
            // 等待一段时间后重试
            await new Promise(resolve => setTimeout(resolve, delay * Math.pow(2, i)));
        }
    }
    
    throw new Error(lastError!.message);
};

// 统一所有请求 baseURL 为 '/'，不再区分不同后端地址
axios.defaults.baseURL = '/api';
axios.defaults.timeout = 10000;

// 响应拦截器
axios.interceptors.response.use(
    (response) => response,
    (error) => {
        const apiError = new ApiError(
            error.response?.data?.message || error.message || '请求失败',
            error.response?.status,
            error.response?.data?.code,
            error.response?.data,
            error.response?.data?.details || error.message,
            error.response?.status >= 500 || error.code === 'NETWORK_ERROR' || error.code === 'TIMEOUT'
        );
        return Promise.reject(apiError);
    }
);

// 通用请求方法
export function request(config: { url: string; method?: string; data?: any; params?: any }) {
    console.log('[request] config:', config);
    return axios.request(config).then(res => {
        console.log('[request] response:', res);
        return res.data;
    });
} 